<?php

class PDbconnect {

    static $cnt;

    public function __construct() {
        if (!isset(self::$cnt)) {
            $mysqlConfig = include $_SERVER['DOCUMENT_ROOT'] . '/src/php/Db_Config.php';
            self::$cnt = mysql_connect($mysqlConfig['servername'] . ':' . $mysqlConfig['port'], $mysqlConfig['username'], $mysqlConfig['password']);
            // 选择数据库
            mysql_select_db($mysqlConfig['db'], self::$cnt);
            // 设置数据库连接编码格式
            mysql_query('SET NAMES UTF8');
        }
    }

    public static function getConnect(){
        return self::$cnt;
    }

    public static function query($sql) {
        $rs = mysql_query($sql) or die("Invalid query: " . mysql_error());
        $output = array();
        while ($row = mysql_fetch_assoc($rs)) {
            array_push($output, $row);
        }
        return $output;
    }

    public static function insert($tb, $data) {
        $keys = '';
        $vals = '';
        foreach ($data as $key => $val) {
            $keys = $keys . $key . ",";
            $vals = $vals . "'" . $val . "',";
        }
        $rs = mysql_query("INSERT INTO " . $tb . " (" . rtrim($keys, ',') . ") VALUES (" . rtrim($vals, ',') . ")") or die("Invalid query: " . mysql_error());
        return $rs;
    }

    public static function update($tb, $data, $k) {
        $vals = '';
        foreach ($data as $key => $val) {
            if ($val !== '') {
                $vals = $vals . $key . "='" . $val . "',";
            }
        }
        $rs = mysql_query("UPDATE " . $tb . " SET " . rtrim($vals, ',') . " WHERE " . $k) or die("Invalid query: " . mysql_error());
        return $rs;
    }

    public static function delete($tb, $k) {
        $rs = mysql_query("DELETE FROM $tb where $k");
        return $rs;
    }

}

// 单例实例化
new PDbconnect();

